#include "wtlpch.h"

#include "XmlConfig.h"

CXmlConfig::~CXmlConfig()
{
	//Clear all the allocated resource
	ATLASSERT(m_pXmlRootFile != NULL);

	delete (ConfigGroup*)m_pXmlRootFile->pxmlRoot;
	delete m_pXmlRootFile;
}

void CXmlConfig::SetRootNodeName(LPCWSTR lpcwstrRootNodeName)
{
	ATLASSERT(lpcwstrRootNodeName != NULL);

	//Create the root group and set member
	m_pXmlRootFile = new CLiteXMLPhaser::XMLFile;
	m_pXmlRootFile->pxmlRoot = CreateConfigGroup(lpcwstrRootNodeName);

	//Set the root name for later use
	m_wstrXmlRootName = lpcwstrRootNodeName;
}

void CXmlConfig::FlushConfigsToDisk()
{
	//Make sure we set the root
	ATLASSERT(m_pXmlRootFile != NULL && !m_wstrXmlFileName.empty());

	//The phaser is on the stack, so it's safe to releas xml file
	CLiteXMLPhaser xmlPhaser(m_wstrXmlFileName.c_str(), CLiteXMLPhaser::WRITE_MODE);
	xmlPhaser.writeXMLFile(m_pXmlRootFile);
}

CXmlConfig::ConfigGroup* CXmlConfig::AddToRootGroup(ConfigGroup* pconfGrp)
{
	ATLASSERT(pconfGrp != NULL);

	//Save the prev root group
	ConfigGroup* pGrpPre = m_pXmlRootGroupNow;

	//No Root Group Now, set it as first group
	if(m_pXmlRootGroupNow == NULL)
	{
		static_cast<ConfigGroup*>(m_pXmlRootFile->pxmlRoot)->SetSonGroup(pconfGrp);
	}
	else	//Or set as the sibling group
	{
		m_pXmlRootGroupNow->SetSiblingGroup(pconfGrp);
	}

	//Refresh the current root group
	m_pXmlRootGroupNow = pconfGrp;
	
	return pGrpPre;
}

CXmlConfig::ConfigGroup* CXmlConfig::CreateConfigGroup(LPCWSTR lpcwstrGroupName)
{
	ATLASSERT(lpcwstrGroupName != NULL);

	ConfigGroup* pconfgGroup = new ConfigGroup(lpcwstrGroupName, true, NULL, NULL);
	return pconfgGroup;
}

CXmlConfig::ConfigSection* CXmlConfig::CreateConfigSection(LPCWSTR lpwcstrSectionName, LPCWSTR lpwcstrEntryName, bool isCDATA, CXmlConfig::ConfigGroup** ppConfigGroup)
{
	ATLASSERT(lpwcstrSectionName != NULL && lpwcstrEntryName != NULL && ppConfigGroup != NULL);

	ConfigSection* pConfigSection = new ConfigSection(lpwcstrEntryName, isCDATA);
	*ppConfigGroup = new ConfigGroup(lpwcstrSectionName, false, pConfigSection);

	return pConfigSection;
}

HRESULT CXmlConfig::getNextCDATA(LPCWSTR lpcwstrFileRelName, LPCWSTR lpwszElementPath, LPCWSTR lpwszPropPath, LPWSTR lpwszCDATA, bool bSubCall)
{
	CLiteXMLPhaser xmlPhaser(lpcwstrFileRelName, CLiteXMLPhaser::READ_MODE);
	
	return xmlPhaser.getNextCDATA(lpwszElementPath, lpwszPropPath, lpwszCDATA, bSubCall);
}

HRESULT CXmlConfig::getNextText(LPCWSTR lpcwstrFileRelName, LPCWSTR lpwszElementPath, LPCWSTR lpwszPropPath, LPWSTR lpwszText, bool bSubCall)
{
	CLiteXMLPhaser xmlPhaser(lpcwstrFileRelName, CLiteXMLPhaser::READ_MODE);
	
	return xmlPhaser.getNextText(lpwszElementPath, lpwszPropPath, lpwszText, bSubCall);
}
